/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.games.epkb.controller;

import it.polimi.games.epkb.controller.exceptions.IllegalOrphanException;
import it.polimi.games.epkb.controller.exceptions.NonexistentEntityException;
import it.polimi.games.epkb.controller.exceptions.PreexistingEntityException;
import it.polimi.games.epkb.entityClasses.SensorType;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import it.polimi.games.epkb.entityClasses.ObservedComponent;
import java.util.ArrayList;
import java.util.Collection;
import it.polimi.games.epkb.entityClasses.GpiKpiInstance;
import javax.transaction.UserTransaction;

/**
 *
 * @author plebani
 */
public class SensorTypeJpaController implements Serializable {

    public SensorTypeJpaController(EntityManagerFactory emf) {
        this.utx = null;
        this.emf = emf;
    }

    public SensorTypeJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(SensorType sensorType) throws PreexistingEntityException, Exception {
        if (sensorType.getObservedComponentCollection() == null) {
            sensorType.setObservedComponentCollection(new ArrayList<ObservedComponent>());
        }
        if (sensorType.getGpiKpiInstanceCollection() == null) {
            sensorType.setGpiKpiInstanceCollection(new ArrayList<GpiKpiInstance>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Collection<ObservedComponent> attachedObservedComponentCollection = new ArrayList<ObservedComponent>();
            for (ObservedComponent observedComponentCollectionObservedComponentToAttach : sensorType.getObservedComponentCollection()) {
                observedComponentCollectionObservedComponentToAttach = em.getReference(observedComponentCollectionObservedComponentToAttach.getClass(), observedComponentCollectionObservedComponentToAttach.getObservedComponentPK());
                attachedObservedComponentCollection.add(observedComponentCollectionObservedComponentToAttach);
            }
            sensorType.setObservedComponentCollection(attachedObservedComponentCollection);
            Collection<GpiKpiInstance> attachedGpiKpiInstanceCollection = new ArrayList<GpiKpiInstance>();
            for (GpiKpiInstance gpiKpiInstanceCollectionGpiKpiInstanceToAttach : sensorType.getGpiKpiInstanceCollection()) {
                gpiKpiInstanceCollectionGpiKpiInstanceToAttach = em.getReference(gpiKpiInstanceCollectionGpiKpiInstanceToAttach.getClass(), gpiKpiInstanceCollectionGpiKpiInstanceToAttach.getGpiKpiInstancePK());
                attachedGpiKpiInstanceCollection.add(gpiKpiInstanceCollectionGpiKpiInstanceToAttach);
            }
            sensorType.setGpiKpiInstanceCollection(attachedGpiKpiInstanceCollection);
            em.persist(sensorType);
            for (ObservedComponent observedComponentCollectionObservedComponent : sensorType.getObservedComponentCollection()) {
                SensorType oldSensorTypeOfObservedComponentCollectionObservedComponent = observedComponentCollectionObservedComponent.getSensorType();
                observedComponentCollectionObservedComponent.setSensorType(sensorType);
                observedComponentCollectionObservedComponent = em.merge(observedComponentCollectionObservedComponent);
                if (oldSensorTypeOfObservedComponentCollectionObservedComponent != null) {
                    oldSensorTypeOfObservedComponentCollectionObservedComponent.getObservedComponentCollection().remove(observedComponentCollectionObservedComponent);
                    oldSensorTypeOfObservedComponentCollectionObservedComponent = em.merge(oldSensorTypeOfObservedComponentCollectionObservedComponent);
                }
            }
            for (GpiKpiInstance gpiKpiInstanceCollectionGpiKpiInstance : sensorType.getGpiKpiInstanceCollection()) {
                SensorType oldIdSensorTypeOfGpiKpiInstanceCollectionGpiKpiInstance = gpiKpiInstanceCollectionGpiKpiInstance.getIdSensorType();
                gpiKpiInstanceCollectionGpiKpiInstance.setIdSensorType(sensorType);
                gpiKpiInstanceCollectionGpiKpiInstance = em.merge(gpiKpiInstanceCollectionGpiKpiInstance);
                if (oldIdSensorTypeOfGpiKpiInstanceCollectionGpiKpiInstance != null) {
                    oldIdSensorTypeOfGpiKpiInstanceCollectionGpiKpiInstance.getGpiKpiInstanceCollection().remove(gpiKpiInstanceCollectionGpiKpiInstance);
                    oldIdSensorTypeOfGpiKpiInstanceCollectionGpiKpiInstance = em.merge(oldIdSensorTypeOfGpiKpiInstanceCollectionGpiKpiInstance);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findSensorType(sensorType.getId()) != null) {
                throw new PreexistingEntityException("SensorType " + sensorType + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(SensorType sensorType) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            SensorType persistentSensorType = em.find(SensorType.class, sensorType.getId());
            Collection<ObservedComponent> observedComponentCollectionOld = persistentSensorType.getObservedComponentCollection();
            Collection<ObservedComponent> observedComponentCollectionNew = sensorType.getObservedComponentCollection();
            Collection<GpiKpiInstance> gpiKpiInstanceCollectionOld = persistentSensorType.getGpiKpiInstanceCollection();
            Collection<GpiKpiInstance> gpiKpiInstanceCollectionNew = sensorType.getGpiKpiInstanceCollection();
            List<String> illegalOrphanMessages = null;
            for (ObservedComponent observedComponentCollectionOldObservedComponent : observedComponentCollectionOld) {
                if (!observedComponentCollectionNew.contains(observedComponentCollectionOldObservedComponent)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain ObservedComponent " + observedComponentCollectionOldObservedComponent + " since its sensorType field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<ObservedComponent> attachedObservedComponentCollectionNew = new ArrayList<ObservedComponent>();
            for (ObservedComponent observedComponentCollectionNewObservedComponentToAttach : observedComponentCollectionNew) {
                observedComponentCollectionNewObservedComponentToAttach = em.getReference(observedComponentCollectionNewObservedComponentToAttach.getClass(), observedComponentCollectionNewObservedComponentToAttach.getObservedComponentPK());
                attachedObservedComponentCollectionNew.add(observedComponentCollectionNewObservedComponentToAttach);
            }
            observedComponentCollectionNew = attachedObservedComponentCollectionNew;
            sensorType.setObservedComponentCollection(observedComponentCollectionNew);
            Collection<GpiKpiInstance> attachedGpiKpiInstanceCollectionNew = new ArrayList<GpiKpiInstance>();
            for (GpiKpiInstance gpiKpiInstanceCollectionNewGpiKpiInstanceToAttach : gpiKpiInstanceCollectionNew) {
                gpiKpiInstanceCollectionNewGpiKpiInstanceToAttach = em.getReference(gpiKpiInstanceCollectionNewGpiKpiInstanceToAttach.getClass(), gpiKpiInstanceCollectionNewGpiKpiInstanceToAttach.getGpiKpiInstancePK());
                attachedGpiKpiInstanceCollectionNew.add(gpiKpiInstanceCollectionNewGpiKpiInstanceToAttach);
            }
            gpiKpiInstanceCollectionNew = attachedGpiKpiInstanceCollectionNew;
            sensorType.setGpiKpiInstanceCollection(gpiKpiInstanceCollectionNew);
            sensorType = em.merge(sensorType);
            for (ObservedComponent observedComponentCollectionNewObservedComponent : observedComponentCollectionNew) {
                if (!observedComponentCollectionOld.contains(observedComponentCollectionNewObservedComponent)) {
                    SensorType oldSensorTypeOfObservedComponentCollectionNewObservedComponent = observedComponentCollectionNewObservedComponent.getSensorType();
                    observedComponentCollectionNewObservedComponent.setSensorType(sensorType);
                    observedComponentCollectionNewObservedComponent = em.merge(observedComponentCollectionNewObservedComponent);
                    if (oldSensorTypeOfObservedComponentCollectionNewObservedComponent != null && !oldSensorTypeOfObservedComponentCollectionNewObservedComponent.equals(sensorType)) {
                        oldSensorTypeOfObservedComponentCollectionNewObservedComponent.getObservedComponentCollection().remove(observedComponentCollectionNewObservedComponent);
                        oldSensorTypeOfObservedComponentCollectionNewObservedComponent = em.merge(oldSensorTypeOfObservedComponentCollectionNewObservedComponent);
                    }
                }
            }
            for (GpiKpiInstance gpiKpiInstanceCollectionOldGpiKpiInstance : gpiKpiInstanceCollectionOld) {
                if (!gpiKpiInstanceCollectionNew.contains(gpiKpiInstanceCollectionOldGpiKpiInstance)) {
                    gpiKpiInstanceCollectionOldGpiKpiInstance.setIdSensorType(null);
                    gpiKpiInstanceCollectionOldGpiKpiInstance = em.merge(gpiKpiInstanceCollectionOldGpiKpiInstance);
                }
            }
            for (GpiKpiInstance gpiKpiInstanceCollectionNewGpiKpiInstance : gpiKpiInstanceCollectionNew) {
                if (!gpiKpiInstanceCollectionOld.contains(gpiKpiInstanceCollectionNewGpiKpiInstance)) {
                    SensorType oldIdSensorTypeOfGpiKpiInstanceCollectionNewGpiKpiInstance = gpiKpiInstanceCollectionNewGpiKpiInstance.getIdSensorType();
                    gpiKpiInstanceCollectionNewGpiKpiInstance.setIdSensorType(sensorType);
                    gpiKpiInstanceCollectionNewGpiKpiInstance = em.merge(gpiKpiInstanceCollectionNewGpiKpiInstance);
                    if (oldIdSensorTypeOfGpiKpiInstanceCollectionNewGpiKpiInstance != null && !oldIdSensorTypeOfGpiKpiInstanceCollectionNewGpiKpiInstance.equals(sensorType)) {
                        oldIdSensorTypeOfGpiKpiInstanceCollectionNewGpiKpiInstance.getGpiKpiInstanceCollection().remove(gpiKpiInstanceCollectionNewGpiKpiInstance);
                        oldIdSensorTypeOfGpiKpiInstanceCollectionNewGpiKpiInstance = em.merge(oldIdSensorTypeOfGpiKpiInstanceCollectionNewGpiKpiInstance);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = sensorType.getId();
                if (findSensorType(id) == null) {
                    throw new NonexistentEntityException("The sensorType with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            SensorType sensorType;
            try {
                sensorType = em.getReference(SensorType.class, id);
                sensorType.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The sensorType with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<ObservedComponent> observedComponentCollectionOrphanCheck = sensorType.getObservedComponentCollection();
            for (ObservedComponent observedComponentCollectionOrphanCheckObservedComponent : observedComponentCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This SensorType (" + sensorType + ") cannot be destroyed since the ObservedComponent " + observedComponentCollectionOrphanCheckObservedComponent + " in its observedComponentCollection field has a non-nullable sensorType field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<GpiKpiInstance> gpiKpiInstanceCollection = sensorType.getGpiKpiInstanceCollection();
            for (GpiKpiInstance gpiKpiInstanceCollectionGpiKpiInstance : gpiKpiInstanceCollection) {
                gpiKpiInstanceCollectionGpiKpiInstance.setIdSensorType(null);
                gpiKpiInstanceCollectionGpiKpiInstance = em.merge(gpiKpiInstanceCollectionGpiKpiInstance);
            }
            em.remove(sensorType);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<SensorType> findSensorTypeEntities() {
        return findSensorTypeEntities(true, -1, -1);
    }

    public List<SensorType> findSensorTypeEntities(int maxResults, int firstResult) {
        return findSensorTypeEntities(false, maxResults, firstResult);
    }

    private List<SensorType> findSensorTypeEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(SensorType.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public SensorType findSensorType(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(SensorType.class, id);
        } finally {
            em.close();
        }
    }

    public int getSensorTypeCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<SensorType> rt = cq.from(SensorType.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
